<template>
  <div>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="coalType">
        <el-select
          multiple
          clearable
          v-model="queryParams.coalType"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in coalTypeList"
            :key="dict.id"
            :label="dict.coalName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易方式" prop="tradingWay">
        <el-select clearable v-model="queryParams.tradingWay" placeholder="请选择" class="!w-300px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_TRADING_WAY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button-group class="ml-4">
          <el-button
            v-for="item in dateTypeList"
            :type="queryParams.timePeriod === item.value ? 'primary' : 'default'"
            @click="dateTypeChange(item.value)"
            :key="item.value"
            >{{ item.label }}</el-button
          >
        </el-button-group>
      </el-form-item>
      <el-form-item label="选择时间" prop="tradingDate">
        <DatePicker
          v-model="queryParams.tradingDate"
          :dateType="queryParams.timePeriod"
          @dataChange="datePickerChange"
        ></DatePicker>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-card class="mt-20px">
      <el-container class="flex space-x-12">
        <div class="h-350px w-full">
          <Echart :height="350" :options="barOptionData" @initReady="initBar" />
        </div>
      </el-container>
    </el-card>
    <el-card class="mt-20px">
      <!-- 列表 -->
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="序号" align="center" width="60" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="时间"
          align="center"
          prop="date"
          min-width="150"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="平均价格(元/吨)" align="center" prop="avgPrice" min-width="150" />
        <el-table-column
          label="平均起拍价格(元/吨)"
          align="center"
          prop="avgStartingPrice"
          min-width="150"
        />
        <el-table-column label="平均溢价(元/吨)" align="center" prop="avgPremium" min-width="150" />
        <el-table-column label="交易量(万吨)" align="center" prop="salesTotal" min-width="150" />
        <el-table-column
          label="交易金额(万元)"
          align="center"
          prop="salesMoneyTotal"
          min-width="150"
        />
      </el-table>
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getPricedStatistics"
      />
    </el-card>
  </div>
</template>
<script setup lang="ts" name="priceAnalysis">
import * as Utils from '@/utils/dict'
import * as dataCenter from '@/api/dataCenter'
import { EChartsOption } from 'echarts'
import { barOption } from '../echarts-data'
import { formatDate } from '@/utils/formatTime'
import { initMonthTimeRange } from '@/utils/common'
import { dateTypeList } from '../dataCenter.data'
import { cloneDeep } from 'lodash-es'

const loading = ref(true) // 列表的加载中
const total = ref(0)
const list = ref([]) // 列表的数据
const queryFormRef = ref()
const barChart = ref()
const message = useMessage()
const barOptionData = reactive<EChartsOption>(barOption) as EChartsOption
const queryParams: Record<string, any> = ref({
  pageNo: 1,
  pageSize: 10,
  coalType: [],
  tradingWay: undefined,
  timePeriod: 'month',
  tradingDate: []
})
const coalTypeList: Record<string, any> = ref([])
const { DICT_TYPE, getIntDictOptions } = reactive(Utils)
let timeTange: any[] = []

/** 查询列表 */

const getList = async () => {
  loading.value = true
  try {
    getPricedStatisticsChart()
    getPricedStatistics()
  } finally {
    loading.value = false
  }
}

const getBody = () => {
  const params = cloneDeep(queryParams.value)
  if (!params.tradingWay) {
    delete params.tradingWay
  }
  if (params.coalType?.length) {
    params.coalId = params.coalType.join(',')
  }
  params.tradingDate = timeTange.join(',')
  delete params.coalType
  return params
}

const getPricedStatisticsChart = async () => {
  const data = cloneDeep(getBody())
  delete data.pageNo
  delete data.pageSize
  const res = await dataCenter.getPricedStatisticsChart(data)
  initBarData(res)
}

const getPricedStatistics = async () => {
  const data = await dataCenter.getPricedStatistics(getBody())
  list.value = data.list || []
  total.value = data.total || 0
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (timeTange.length !== 2) {
    message.warning('选择时间不能为空')
    return
  }
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.value.timePeriod = 'month'
  timeTange = initMonthTimeRange()
  nextTick(() => {
    queryParams.value.tradingDate = formatDate(new Date(), 'YYYY-MM-DD')
  })
  handleQuery()
}

const dateTypeChange = (type) => {
  timeTange = []
  queryParams.value.timePeriod = type
  if (type === 'daterange') {
    queryParams.value.tradingDate = []
  } else {
    queryParams.value.tradingDate = undefined
  }
}

const datePickerChange = ($event) => {
  timeTange = $event
}

const initBar = (chart) => {
  barChart.value = chart
}

const initBarData = (data) => {
  barChart.value.setOption({
    title: {
      text: ''
    },
    grid: {
      top: 30,
      bottom: 50
    },
    legend: {
      data: getLegendData(data.columnChartMap)
    },
    xAxis: {
      data: data.date || []
    },
    series: getSeriesData(data.columnChartMap)
  })
}

const getLegendData = (data) => {
  return Object.keys(data)
}

const getSeriesData = (data) => {
  return getLegendData(data).map((key) => {
    return {
      name: key,
      type: 'bar',
      stack: '总量',
      barMaxWidth: 30,
      data: data[key]
    }
  })
}

const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

/** 初始化 **/
onMounted(() => {
  queryParams.value.tradingDate = formatDate(new Date(), 'YYYY-MM-DD')
  timeTange = initMonthTimeRange()
  bidCoalManageList()
  getList()
})
</script>
